#include <stdio.h>
#include <stdlib.h>
#include <memory.h>
#include <string.h>
#include "../head/default.h"         //define 宏定义及static变量                                      
#include "../head/log.h"         //define 宏定义及static变量 
#include "../head/md5.h"         //define 宏定义及static变量 


void f_logging(enum LogLevel level, const char *fmt, ...);
int f_get_md5(char str[], char res_md5[]);
int f_my_strncpy(char *string, int n);

int f_my_system(const char *str, const char md5[], char result[]) {
    //执行系统命令, 并返回正确及错误输出, 执行前会先验证client传过来的命令md5是否正常
    memset(result, 0x00, sizeof(result));
    char cmd[VAR_MAX_LEN], cmd_tmp[VAR_MAX_LEN];
    memcpy(cmd, str, strlen(str) + 1);
    memcpy(cmd_tmp, str, strlen(str) + 1);
    char server_md5[VAR_MAX_LEN];
    memset(server_md5, 0x00, sizeof(server_md5));
    f_get_md5(cmd, server_md5);
    if (strcmp(server_md5, md5) != 0) {
        f_logging(ERROR, "SERVER --> The MD5 validation of this command does not pass!");
        return -3;;
    }
    
    //strcat(cmd," 2>&1"); //重新封装命令, 将错误输出也打印出来
    sprintf(cmd, "%s 2>&1", cmd);
    char buf[VAR_MAX_LEN] = {0};
    FILE *fp = NULL;

    if( (fp = popen(cmd, "r")) == NULL ) {
        strcat(result, "Popen error");
        return -2;
    }

    memset(buf, 0x00, sizeof(buf));   //先清空这个内存地址, 避免结果被污染
    int c = 0;
    char log_info[VAR_MAX_LEN] = "WARN --> This return exceeds the maximum limit!";
    while (fgets(buf, sizeof(buf) - 1, fp)) {
        c = c + (int)strlen(buf);
        if ((int)strlen(result) + (int)strlen(buf) > RES_MAX_LEN - 1000){ 
            f_logging(WARN, log_info);
            strcat(result, "\n\n");          //加两个换行, 为了使后面的log_info更醒目
            strcat(result, log_info);        //log_info放在res
            strcat(result, "\n");            //加个换行
            break;
        } else {
            strcat(result, buf);             //读取命令的输出, 包括错误输出
        }
    }

    memset(buf, 0x00, sizeof(buf));
    int status = pclose(fp);
    if (WEXITSTATUS(status) != 0) {
        result[strlen(result) - 1] = 0;
        strcat(result, " [ ");
        strcat(result, str);
        strcat(result, " ]. ");
        return -1;
    }
    return 0;
}

